/*

	初始化参数
	config = {
		adultCount: 4
		arr: "三亚"
		backDate: "2018-11-18"
		backFlightArr: "北京"
		childCount: 0
		dep: "北京"
		goBackDateList: [Array(2)]
		goDate: "2018-11-14"
		handler: init [span.btn, context: span.btn]
		pId: "3477232601"
		takeoffDate: "2018-11-14"
		toFlightArr: "三亚"
	}
 */
require('common/smallCalendar/index');
const testData = {
  "status": 0,
  "message": 0,
  "data": {
    "packageFlights": {
      "page": 20,
      "total": 31,
      "flights": [
        [
          {
            "fid": 1234,
            "packKey": "KN5885|17784",
            "flightCode": "KN5885",
            "fltno": "KN5885",
            "cab": "X",
            "cabType": "经济舱",
            "airline": "中联航",
            "plane": "波音737(中)",
            "date": "2018-11-14",
            "fly": "直飞",
            "depTime": "13:45",
            "arrTime": "17:50",
            "flyTime": "4小时5分",
            "day": "",
            "overnight": 0,
            "depAir": "南苑机场",
            "arrAir": "凤凰机场",
            "depTerm": null,
            "arrTerm": "",
            "depCity": "北京",
            "arrCity": "三亚",
            "depCode": "NAY",
            "arrCode": "SYX",
            "diff": null,
            "supplierId": "17784",
            "airLineId": "0",
            "journeyType": null,
            "orgDiff": null,
            "totalPrice": "￥2104",
            "flightToken": "sdfasdf",
            "sortPrice": 2104,
            "earlyGoLateReturn": "",
            "lowestPriceFlight": "",
            "dfid": null,
            "type": "去程",
            "policy": null,
            "adtPrice": 1052,
            "chdPrice": 1002,
            "adtSave": null,
            "chdSave": null,
            "packType": null,
            "stop": false,
            "stayTime": null,
            "stopCity": null,
            "airCompanyLogo": "//source.qunarzz.com/site/images/airlines/small/KN.gif",
            "discountPrice": null,
            "childDiscountPrice": null,
            "discountInfo": null,
            "childDiscountInfo": null
          },
          {
            "fid": 2345,
            "packKey": "KN5885|17784",
            "flightCode": "KN5885",
            "fltno": "KN5885",
            "cab": "X",
            "cabType": "经济舱",
            "airline": "中联航",
            "plane": "波音737(中)",
            "date": "2018-11-14",
            "fly": "直飞",
            "depTime": "13:45",
            "arrTime": "17:50",
            "flyTime": "4小时5分",
            "day": "",
            "overnight": 0,
            "depAir": "南苑机场",
            "arrAir": "凤凰机场",
            "depTerm": null,
            "arrTerm": "",
            "depCity": "北京",
            "arrCity": "三亚",
            "depCode": "NAY",
            "arrCode": "SYX",
            "diff": null,
            "supplierId": "17784",
            "airLineId": "0",
            "journeyType": null,
            "orgDiff": null,
            "totalPrice": "￥2104",
            "flightToken": "sdfasdf",
            "sortPrice": 2104,
            "earlyGoLateReturn": "",
            "lowestPriceFlight": "",
            "dfid": null,
            "type": "去程",
            "policy": null,
            "adtPrice": 1052,
            "chdPrice": 1002,
            "adtSave": null,
            "chdSave": null,
            "packType": null,
            "stop": false,
            "stayTime": null,
            "stopCity": null,
            "airCompanyLogo": "//source.qunarzz.com/site/images/airlines/small/KN.gif",
            "discountPrice": null,
            "childDiscountPrice": null,
            "discountInfo": null,
            "childDiscountInfo": null
          }
        ]
      ],
      "filter": [
        {
          "key": "company",
          "value": "航空公司",
          "list": [
            {
              "key": "金鹿航空",
              "value": "金鹿航空"
            },
            {
              "key": "深航",
              "value": "深航"
            },
            {
              "key": "中联航",
              "value": "中联航"
            },
            {
              "key": "国航",
              "value": "国航"
            },
            {
              "key": "昆明航空",
              "value": "昆明航空"
            },
            {
              "key": "东航",
              "value": "东航"
            },
            {
              "key": "南航",
              "value": "南航"
            },
            {
              "key": "海航",
              "value": "海航"
            },
            {
              "key": "厦航",
              "value": "厦航"
            }
          ]
        },
        {
          "key": "time",
          "value": "起飞时间",
          "list": [
            {
              "key": "1",
              "value": "6至12点"
            },
            {
              "key": "2",
              "value": "12至13点"
            },
            {
              "key": "3",
              "value": "13至18点"
            },
            {
              "key": "4",
              "value": "18至24点"
            }
          ]
        },
        {
          "key": "stop",
          "value": "直飞",
          "list": [
            {
              "key": "直飞",
              "value": "直飞"
            }
          ]
        }
      ]
    },
    "singleToFlights": {
      "page": 20,
      "total": 31,
      "flights": [
        [
          {
            "fid": 345,
            "packKey": "KN5885|17784",
            "flightCode": "KN5885",
            "fltno": "KN5885",
            "cab": "X",
            "cabType": "经济舱",
            "airline": "中联航",
            "plane": "波音737(中)",
            "date": "2018-11-14",
            "fly": "直飞",
            "depTime": "13:45",
            "arrTime": "17:50",
            "flyTime": "4小时5分",
            "day": "",
            "overnight": 0,
            "depAir": "南苑机场",
            "arrAir": "凤凰机场",
            "depTerm": null,
            "arrTerm": "",
            "depCity": "北京",
            "arrCity": "三亚",
            "depCode": "NAY",
            "arrCode": "SYX",
            "diff": null,
            "supplierId": "17784",
            "airLineId": "0",
            "journeyType": null,
            "orgDiff": null,
            "totalPrice": "￥2104",
            "flightToken": "sdfasdf",
            "sortPrice": 2104,
            "earlyGoLateReturn": "",
            "lowestPriceFlight": "",
            "dfid": null,
            "type": "去程",
            "policy": null,
            "adtPrice": 1052,
            "chdPrice": 1002,
            "adtSave": null,
            "chdSave": null,
            "packType": null,
            "stop": false,
            "stayTime": null,
            "stopCity": null,
            "airCompanyLogo": "//source.qunarzz.com/site/images/airlines/small/KN.gif",
            "discountPrice": null,
            "childDiscountPrice": null,
            "discountInfo": null,
            "childDiscountInfo": null
          }
        ]
      ],
      "filter": [
        {
          "key": "company",
          "value": "航空公司",
          "list": [
            {
              "key": "金鹿航空",
              "value": "金鹿航空"
            },
            {
              "key": "深航",
              "value": "深航"
            },
            {
              "key": "中联航",
              "value": "中联航"
            },
            {
              "key": "国航",
              "value": "国航"
            },
            {
              "key": "昆明航空",
              "value": "昆明航空"
            },
            {
              "key": "东航",
              "value": "东航"
            },
            {
              "key": "南航",
              "value": "南航"
            },
            {
              "key": "海航",
              "value": "海航"
            },
            {
              "key": "厦航",
              "value": "厦航"
            }
          ]
        },
        {
          "key": "time",
          "value": "起飞时间",
          "list": [
            {
              "key": "1",
              "value": "6至12点"
            },
            {
              "key": "2",
              "value": "12至13点"
            },
            {
              "key": "3",
              "value": "13至18点"
            },
            {
              "key": "4",
              "value": "18至24点"
            }
          ]
        },
        {
          "key": "stop",
          "value": "直飞",
          "list": [
            {
              "key": "直飞",
              "value": "直飞"
            }
          ]
        }
      ]
    },
    "singleBackFlights": {
      "page": 20,
      "total": 31,
      "flights": [
        [
          {
            "fid": 456,
            "packKey": "KN5885|17784",
            "flightCode": "KN5885",
            "fltno": "KN5885",
            "cab": "X",
            "cabType": "经济舱",
            "airline": "中联航",
            "plane": "波音737(中)",
            "date": "2018-11-14",
            "fly": "直飞",
            "depTime": "13:45",
            "arrTime": "17:50",
            "flyTime": "4小时5分",
            "day": "",
            "overnight": 0,
            "depAir": "南苑机场",
            "arrAir": "凤凰机场",
            "depTerm": null,
            "arrTerm": "",
            "depCity": "北京",
            "arrCity": "三亚",
            "depCode": "NAY",
            "arrCode": "SYX",
            "diff": null,
            "supplierId": "17784",
            "airLineId": "0",
            "journeyType": null,
            "orgDiff": null,
            "totalPrice": "￥2104",
            "flightToken": "sdfasdf",
            "sortPrice": 2104,
            "earlyGoLateReturn": "",
            "lowestPriceFlight": "",
            "dfid": null,
            "type": "去程",
            "policy": null,
            "adtPrice": 1052,
            "chdPrice": 1002,
            "adtSave": null,
            "chdSave": null,
            "packType": null,
            "stop": false,
            "stayTime": null,
            "stopCity": null,
            "airCompanyLogo": "//source.qunarzz.com/site/images/airlines/small/KN.gif",
            "discountPrice": null,
            "childDiscountPrice": null,
            "discountInfo": null,
            "childDiscountInfo": null
          }
        ]
      ],
      "filter": [
        {
          "key": "company",
          "value": "航空公司",
          "list": [
            {
              "key": "金鹿航空",
              "value": "金鹿航空"
            },
            {
              "key": "深航",
              "value": "深航"
            },
            {
              "key": "中联航",
              "value": "中联航"
            },
            {
              "key": "国航",
              "value": "国航"
            },
            {
              "key": "昆明航空",
              "value": "昆明航空"
            },
            {
              "key": "东航",
              "value": "东航"
            },
            {
              "key": "南航",
              "value": "南航"
            },
            {
              "key": "海航",
              "value": "海航"
            },
            {
              "key": "厦航",
              "value": "厦航"
            }
          ]
        },
        {
          "key": "time",
          "value": "起飞时间",
          "list": [
            {
              "key": "1",
              "value": "6至12点"
            },
            {
              "key": "2",
              "value": "12至13点"
            },
            {
              "key": "3",
              "value": "13至18点"
            },
            {
              "key": "4",
              "value": "18至24点"
            }
          ]
        },
        {
          "key": "stop",
          "value": "直飞",
          "list": [
            {
              "key": "直飞",
              "value": "直飞"
            }
          ]
        }
      ]
    }
  }
}
const T = {
  isEmptyObject({obj}){
    let result = false,
      typeString = Object.prototype.toString.call(obj);
    if( typeString == "[object String]" || typeString == "[object Array]"){
      if(!obj.length){
        result = true;
      }
    }
    if( typeString == "[object Object]"){
      if(!obj.length){
        let arr = Object.keys(obj);
        if(!arr.length){
          result = true;
        }
      }
    }
    return result;
  },
  getFilter(arr,type){
    if(arr.length){
      for(let i = 0;i<arr.length;i++){
        if(arr[i].key == type){
          return arr[i].list;
        }
      }
    }
  }
}

//各种选择器
const K = {
  departureDateBtnClass : "[data-node='departureDateSelectBox']",//起飞日期选择器
  popContainerClass : ".js-calendar-container", //日历框父容器
  selectFilter : '[data-node="filterShower"]', //下拉框选择器
  filterOptions : '[data-node="options"]', //下拉框选项列表
  filterVal : '[data-filterval]', // 下拉框选择的值（input)
  selectedFilterBtn : '[data-btn="delFilterItem"]' //被选择的过滤器
};
require("./tmpl/moreSysFlightPop.mustache");
require("./tmpl/moreSysFlight.mustache");
require("./tmpl/moreSysFlightLoading.mustache");
require("./tmpl/moreSysFlightItem.mustache");

//新增排序类,
class Sort{
  constructor(){
    this.sorts = {
      go : $.extend({},Sort.defaultSortElement),
      back : $.extend({},Sort.defaultSortElement)
    };
    //this.setSort("go",{time:true});
    //this.setSort("back",{time:true});
    this.setSort("go",{default:true});
    this.setSort("back",{default:true});
  };
  setSort(dir,config){
    this.clearDirSort(dir);
    $.extend(this.sorts[dir],config);
    this.createSortFunc(dir);
  };
  clearDirSort(dir){
    this.sorts[dir].default = false;
    this.sorts[dir].money = false;
    this.sorts[dir].time = false;
    this.sorts[dir].ASC = true;
  };
  createSortFunc(dir){
    let str = "",
      {money,time,ASC} = this.sorts[dir],
      compareSymbol = ASC ? "<" : ">";
    if(money){
      str = ASC ? "return a[0].adult_price - b[0].adult_price;" : "return b[0].adult_price - a[0].adult_price;";
    };
    if(time){
      str = "return (a[0].dep_time" + compareSymbol + "b[0].dep_time) ? -1 : 1;";
    };
    if(str === ""){str ="return -1;"}
    this.sorts[dir].func = new Function("a","b",str);
  }
}
Sort.defaultSortElement = {money:false,time:false,ASC:true};
//新增过滤类
class Filter{
  constructor(){

    this.filters = [];//{dir:"go|back",name:"",val:"",testStr, isGo:true|false}
  };
  add(dir,name,val){
    let testStr = "";
    switch(name){
      case "airlines":
        testStr = dir+"Flight.airline_short === '" +val +"'";
        break;
      case "departureTime":
        var rangeVal = val.split("-");
        testStr = "(" + dir + "Flight.dep_time >= '" + rangeVal[0] + "'&&" + dir + "Flight.dep_time <= '" + rangeVal[1] + "')";
        break;
    }
    this.filters.push({dir,name,val,testStr,isGo : dir === "go"});
    // let prop = this.filters[dir];
    // if(prop[name]){
    // 	prop[name].push(val);
    // }else{
    // 	prop[name] = [val];
    // };
  };
  remove(__dir,__name,__val){
    for(let i =0,l = this.filters.length;i<l;i++){
      let {dir,name,val} = this.filters[i];
      if(	dir == __dir &&
        name == __name &&
        val == __val
      ){
        this.filters.splice(i,1);
        return;
      }
    };
  }
  createFilterFunc(){
    let ruleArr = [],ruleObj={},str;
    $.each(this.filters,function(i,n){
      let propString = n.dir + "_" + n.name;
      n.ind = i;
      if(ruleObj[propString] !== undefined){
        //说明此类规则已存在
        ruleArr[ruleObj[propString]].push(n.testStr);
      }else{
        ruleArr.push([n.testStr]);
        ruleObj[propString] = ruleArr.length - 1;
      }
    });
    //降维处理数据
    $.each(ruleArr,function(i,n){
      ruleArr[i] = "(" + n.join("||") + ")";
    })
    return new Function('goFlight,backFlight',"return " + ruleArr.join("&&"));
  };
  //返回true，说明是匹配的；false：不匹配

  // let prop = this.filters[dir][name];
  // if(prop && prop.length){
  // 	// $.each(prop,function(i,n){

  // 	// });
  // };
  // if(!prop || !prop.length){
  // 	delete this.filters[dir][name];
  // }

};


const moreFlight = {
  init(config){
    if(!this.inited){
      // 首次进入
      this.config = config;
      this.filters = new Filter();
      this.sorts = new Sort();
      this.selected = {
        go:[],
        back:[],
        round:[]
      };//选定的机票
      this.initEle();
      this.initEvt();
      this.requestFlights();
    }else{
      // 之后的每次进入
      this.render();
      // 判断是否需要重新请求接口
      this.reload(config);
    }
    this.showPopUp();
    this.$contentDom.scrollTop(0);
    this.inited = true;
  },
  showPopUp(){
    let {handler:$dom} = this.config;
    this.documentBody.hide();
    var width=this.$popup.width(),left=$(window).width();
    let top = ($(window).height() - this.$popup.height()) /2;
    this.$popup.css({
      position:'fixed',
      top:top,
      left:(left-width)/2,
      zIndex:'3000'
    }).show();
    this.$mask.show();
  },
  initEvt(){
    let _this = this;
    //关闭弹窗
    this.$popup.on('click','.js_i_p_close',()=>{
      this.closePopUp();
    });

    //选航班按钮
    this.$popup.on("click",".js_l_s_btn",function(e){
      let $btn = $(this),
        $itemDom = $btn.closest("[repeater-ui='item']"),
        dir = $btn.data("type"),
        flightId = $itemDom.data("id") + "";
      _this.selectedFlight({$btn,$itemDom,flightId,dir});
    });

    //切换自由组合和往返套餐
    this.$popup.on('click','.js_f_nav',()=>{
      $('.ja_f_nav').removeClass('cur');
      $(this).addClass('cur');
      let $btn = $(this),
        type = $btn.data('dir');
      this.requestFlights({type});
      if(type == 'round'){
        this.$popup.find('.round-type').show();
        this.$popup.find('.single-type').hide();
      }else{
        this.$popup.find('.round-type').hide();
        this.$popup.find('.single-type').show();
      }
    });

    //收起，展开底部其他所有航班按钮
    this.$popup.on('click','.js_more_btn',(e)=>{
      e.preventDefault();
      let $btn = $(this),
        dir = $btn.data('type');
      this.switchBottomBtn({dir});
    });


  },
  /*
    初始化变量
     */
  initEle(){
    this.$popup = $(QTMPL.moreSysFlightPop.render());
    this.$mask = QNR.module.mask;
    this.documentBody = $("#confirmOrder");
    this.$contentDom = this.$popup.find('[data-type="content"]');
    $("body").append(this.$popup);
    this.flights = {
      allGoFlights:[],
      allBackFlights:[],
      allRoundFlights:[],
      goAirlines:[],
      backAirlines:[],
      goTimes:[],
      backTimes:[],
      allFlights:{},
      defaultData:{}		//接口返回的默认数据
    }
  },
  closePopUp(){
    this.documentBody.show();
    this.$popup.hide();
    this.$mask.hide();
  },
  render(data){
    if(data){
      this.$contentDom.html(QTMPL.moreSysFlight.render(data));
      if(data.isDefaultRound){
        this.$popup.find('.round-type').show();
        this.$popup.find('.single-type').hide();
      }else{
        this.$popup.find('.round-type').hide();
        this.$popup.find('.single-type').show();
      }
    }else{
      this.$contentDom.html(QTMPL.moreSysFlightLoading.render(this.config));
    }
  },
  reload(config){
    let {
        dep : _dep,
        toFlightArr : _toFlightArr,
        arr : _arr,
        backFlightArr : _backFlightArr,
        adultCount : _adultCount,
        childCount : _childCount,
        goDate : _goDate,
        backDate : _backDate
      } = this.config,
      {
        dep : dep_,
        toFlightArr : toFlightArr_,
        arr : arr_,
        backFlightArr : backFlightArr_,
        adultCount : adultCount_,
        childCount : childCount_,
        goDate : goDate_,
        backDate : backDate_
      } = config;
    if( _dep === dep_ &&
      _toFlightArr === toFlightArr_ &&
      _backFlightArr === backFlightArr_ &&
      _arr === arr_ &&
      _adultCount === adultCount_ &&
      _childCount === childCount_ &&
      _goDate === goDate_ &&
      _backDate === backDate_ ){
      //参数未变动，上一次请求的数据重新渲染
      this.filters = new Filter();
      this.sorts = new Sort();
      this.allFlights = this.defaultData;
      this.getFlight(this.defaultData);
    }else{
      //请求参数变动，需要重新请求接口
      $.extend(this.config,config);
      this.requestFlights();
    }
  },
  requestFlights(obj = {},$itemDom,dir){
    let {dep,arr,adultCount,childCount,goDate,backDate,takeoffDate,pId}=this.config;
    let reqData = $.extend({tuId:QNR.productInfo.tuId},{dep,arr,adultCount,childCount,goDate,backDate,takeoffDate,pId},obj);
    let _this = this,flights = [];
    $.ajax({
      url: "/user/product/ddr/flight/change.json",
      data:reqData,
      dataType: 'json',
      success: (resp)=>{
        resp = testData;
        const {data} = resp;
        if(data && !T.isEmptyObject(data)){
          // 默认进入
          if(!reqData.type){
            //缓存全局的配地信息
            _this.filters.filters = [];
            _this.flights.goAirlines = [];
            _this.flights.backAirlines = [];
            _this.flights.allFlights = _this.flights.defaultData = resp.data;
            _this.getFlight(resp.data);
          }else{
            //选择去程或者回程重新请求
            //reqData.type要渲染的方向
            if(reqData.type == 'go'){
              flights = (resp.data && resp.data.singleToFlights && resp.data.singleToFlights.flights) || [];
            }
            _this.renderSingleDirFlights({dir,flights,$itemDom});
          }

        }else{
          //nothings

        }
      },
      error: (XMLHttpRequest, textStatus, errorThrown)=>{
        if (textStatus == 'timeout') {
          console && console.log && console.log("更多机票查询异常");
        }
      }
    });
  },
  /*
        整理接口数据
     */
  getFlight(data){
    let isDefaultRound,
      noRoundFlights,
      noGoFlights,
      noBackFlights,
      goFlightsCount,
      backFlightsCount,
      packageFlightsObj = data.packageFlights,
      goFlightsObj = data.singleToFlights,
      backFlightsObj = data.singleBackFlights;
    //往返套餐
    if(packageFlightsObj){
      // 默认是往返套餐还是自由组合
      if(T.isEmptyObject(packageFlightsObj)){
        isDefaultRound = false;
      }else{
        isDefaultRound = true;
      }

      if(packageFlightsObj.flights && packageFlightsObj.flights.length){
        noRoundFlights = false;
        let obj={},list = [];
        $.each(packageFlightsObj.flights,(key,item)=>{
          if(item.length){
            obj.go = item[0];
            obj.back = item[1];
            list.push(obj);
          }
        })
        this.flights.allRoundFlights = list;
      }else{
        noRoundFlights = true;
        this.flights.allRoundFlights = [];
      }
    }

    //自由组合去程
    if(goFlightsObj){
      if(goFlightsObj.flights && goFlightsObj.flights.length){
        noGoFlights = false;
        this.flights.allGoFlights = goFlightsObj.flights;
        this.flights.goAirlines = T.getFilter(goFlightsObj.filter,'company');
        this.flights.goTimes = T.getFilter(goFlightsObj.filter,'time');
        goFlightsCount = goFlightsObj.total;
      }else{
        noGoFlights = true;
      }
    }

    //自由组合回程
    if(backFlightsObj){
      if(backFlightsObj.flights && backFlightsObj.flights.length){
        noBackFlights = false;
        this.flights.allBackFlights = backFlightsObj.flights;
        this.flights.backAirlines = T.getFilter(backFlightsObj.filter,'company');
        this.flights.backAirlines = T.getFilter(backFlightsObj.filter,'time');
        backFlightsCount = backFlightsObj.total;
      }else{
        noBackFlights = true;
      }
    }

    let {dep,toFlightArr,arr,backFlightArr,goDate,backDate} = this.config,
      {allGoFlights,allBackFlights,allRoundFlights,goAirlines,backAirlines,goTimes,backTimes} = this.flights;
    this.render({
      dep,toFlightArr,arr,backFlightArr,goDate,backDate,
      isDefaultRound,
      goAirlines,backAirlines,goTimes,backTimes,
      noRoundFlights,
      noGoFlights,
      noBackFlights,
      goFlightsCount,
      backFlightsCount,
      allGoFlights,
      allBackFlights,
      allRoundFlights,
      hasFilters : this.filters.filters.length,
      filters : this.filters.filters,
      sorts : this.sorts.sorts
    })
  },
  //选择航班
  selectedFlight({$btn,$itemDom,flightId,dir}){
    if(dir == 'round'){
      //往返套餐
      let {flights} = this.getSelectedFlight({flightId,dir,flightsType:'allRoundFlights'});
      this.selected[dir] = flights;
      this.renderAfterPairSuccess({dir,$itemDom});
    }else{
      // 自由组合
      let type = '',flightsType,
        rid = dir == 'go'?'back':'go';
      this.filters = new Filter();
      this.sorts = new Sort();
      //去程回程都没有选择
      if(dir == 'go'){
        type = 'back';
        flightsType = 'allGoFlights';
      }else if(dir == 'back'){
        flightsType = 'allBackFlights';
        type = 'go';
      }
      let {supplierId,flights} = this.getSelectedFlight({flightId,dir,flightsType});
      if((!this.selected[dir].length && !this.selected[rid].length) || (this.selected[dir].length && this.selected[rid].length)){
        this.requestFlights({type,supplierId},$itemDom,dir);
      }else if(!this.selected[dir].length && this.selected[rid].length){
        // 已选择完去程或者回程
        this.renderAfterPairSuccess({dir,$itemDom})
      }
      this.selected[dir] = flights;
    }
  },
  //获取选中的航班的数据
  getSelectedFlight({flightId,dir,flightsType}){
    let flights = [],supplierId;
    $.each(this.flights[flightsType],(item)=>{
      if(item.fid == flightId){
        flights.push(item);
        supplierId = item.supplierId;
      }
    });
    return {
      flights,
      supplierId
    };
  },

  //获得各种dom选择器
  _getSelector(dir){
    //本方向,反方向飞机列表dom id
    let [dirListHtmlSelector,ridListHtmlSelector,roundListHtmlSelector] = ["#leftMoreSysFlightsList","#rightMoreSysFlightsList",'#roundMoreSysFlightsList'],
      //本方向,反方向尾部提示(收起,等)
      [dirBottomHtmlSelector,ridBottomHtmlSelector,roundBottomHtmlSelector] = [".js_left_bottom_tip",".js_right_bottom_tip",'.js_round_bottom_tip'],
      //本方向,反方向已选区
      [dirSelectedAreaHtmlSelector,ridSelectedAreaHtmlSelector,roundSelectedAreaHtmlSelector] = ["[data-node='seletedGoBlk']","[data-node='seletedBackBlk']","[data-node='seletedRoundBlk']"],
      //本方向,反方向已选区航班数量汇总
      [dirTotalNum,ridTotalNum] = [".js_left_totalNum",".js_right_totalNum"];

    if(dir === "go"){
      return {
        dirListHtmlSelector,
        ridListHtmlSelector,
        dirBottomHtmlSelector,
        ridBottomHtmlSelector,
        dirSelectedAreaHtmlSelector,
        ridSelectedAreaHtmlSelector,
        dirTotalNum,
        ridTotalNum
      };
    }else if(dir == 'back'){
      return {
        dirListHtmlSelector : ridListHtmlSelector,
        ridListHtmlSelector : dirListHtmlSelector,
        dirBottomHtmlSelector : ridBottomHtmlSelector,
        ridBottomHtmlSelector : dirBottomHtmlSelector,
        dirSelectedAreaHtmlSelector : ridSelectedAreaHtmlSelector,
        ridSelectedAreaHtmlSelector : dirSelectedAreaHtmlSelector,
        dirTotalNum : ridTotalNum,
        ridTotalNum : dirTotalNum
      };
    }else{
      return {
        dirListHtmlSelector:roundListHtmlSelector, //往返方向列表dom id
        dirBottomHtmlSelector:roundBottomHtmlSelector, //往返方向尾部提示(收起,等)
        dirSelectedAreaHtmlSelector :roundSelectedAreaHtmlSelector
      };
    }
  },
  //单独渲染本方向的机票列表 $itemDom:本方向选中的dom,用于改样式及复制到已选区.
  renderSingleDirFlights({dir,flights,$itemDom}){
    //各种dom选择器
    let {
      dirListHtmlSelector, //正方向列表dom id
      ridListHtmlSelector, //反方向列表dom id
      dirBottomHtmlSelector, //正方向尾部提示(收起,等)
      ridBottomHtmlSelector, //反方向尾部提示(收起,等)
      dirSelectedAreaHtmlSelector, //本方向已选区
      ridSelectedAreaHtmlSelector, //反方向已选区
      dirTotalNum
    } = this._getSelector(dir);

    //正方向操作1 : 复制选中的飞机dom
    let $cloneDom = $itemDom.clone();
    //正方向操作2 : 将复制的dom的显示状态改变
    $cloneDom.find("[item='selecttip']").show();
    $cloneDom.find(".js_l_s_btn").removeClass("check").addClass("ok").html("");
    //正方向操作3 : 清空已选区,复制DOM到已选区
    this.$popup.find(dirSelectedAreaHtmlSelector).html("").append($cloneDom).show();
    //正方向操作4 : 将选中的飞机dom隐藏起来
    $itemDom.hide();
    //正方向操作5 : 淡隐list Dom
    this.$popup.find(dirListHtmlSelector).slideUp("fast");
    //正方向尾部操作1
    this.$popup.find(dirBottomHtmlSelector).show().find('.js_p_l_more').addClass('expend').find(".js_more_text").text("查看其它所有航班");

    //反方向操作1 : 清空选区
    this.$popup.find(ridSelectedAreaHtmlSelector).html("").hide();
    //反方向操作2 : 重新渲染列表
    this.$popup.find(ridListHtmlSelector).html(QTMPL.moreSysFlightItem.render({flights,isGo : dir !== "go"})).slideDown("fast");
    //反方向操作3 : 更新航班总数
    this.$popup.find(dirTotalNum).text(flights.length);

    //反方向操作4: 隐藏收起dom块
    this.$popup.find(ridBottomHtmlSelector).hide();
  },
  //配对成功之后的渲染:先选了1个方向的飞机,后选了反方向飞机,这两飞机在配对(打包)信息数组里面是一对,算配对成功
  // 1.处理本方向的DOM,2.弹出确认按钮及相关
  renderAfterPairSuccess({dir,$itemDom}){
    //各种dom选择器
    let {
      dirListHtmlSelector, //正方向列表dom id
      dirBottomHtmlSelector, //正方向尾部提示(收起,等)
      dirSelectedAreaHtmlSelector //本方向已选区
    } = this._getSelector(dir);
    //正方向操作1 : 复制选中的飞机dom
    let $cloneDom = $itemDom.clone();
    //正方向操作2 : 将复制的dom的显示状态改变
    $cloneDom.find("[item='selecttip']").show();
    $cloneDom.find(".js_l_s_btn").removeClass("check").addClass("ok").html("");
    //正方向操作3 : 清空已选区,复制DOM到已选区
    this.$popup.find(dirSelectedAreaHtmlSelector).html("").append($cloneDom).show();
    //正方向操作4 : 将选中的飞机dom隐藏起来
    $itemDom.hide();
    //正方向操作5 : 淡隐list Dom
    this.$popup.find(dirListHtmlSelector).slideUp("fast");
    //正方向尾部操作1
    this.$popup.find(dirBottomHtmlSelector).show().find('.js_p_l_more').addClass('expend').find(".js_more_text").text("查看其它所有航班");
    this.changeComfirmBlk(true);
  },
  // 底部价格的显隐
  changeComfirmBlk(isOpen){
    let {
        go :
          [

            {
              adtPrice : goAdultPrice , chdPrice : goChildPrice
            },
            ...goMore
          ] = [{}],
        back :
          [

            {
              adtPrice : backAdultPrice , chdPrice : backChildPrice
            },
            ,...backMore
          ] = [{}],
        round :
          [
            {
              adtPrice : roundAdultPrice , chdPrice : roundChildPrice
            },
            ,...roundMore
          ] = [{}]
      } = this.selected,
      $dom = this.$popup.find(".js_p_l_yd");
    if(isOpen){
      $dom.find("[item='aPrice']").text( goAdultPrice + backAdultPrice );
      $dom.find("[item='cPrice']").text( goChildPrice + backChildPrice );
      $dom.show();
    }else{
      $dom.hide();
    }
  },
  // 收起展开按钮
  switchBottomBtn({dir}){
    let {
        dirListHtmlSelector, //正方向列表dom id
        dirBottomHtmlSelector //正方向尾部提示(收起,等)
      } = this._getSelector(dir),
      listBox = this.$popup.find(dirListHtmlSelector),
      bottomBtn = this.$popup.find(dirBottomHtmlSelector);
    if(listBox.is(':visible')){
      listBox.hide();
      bottomBtn.find('js_p_l_more').addClass('expend').find(".js_more_text").text("查看其它所有航班");
    }else{
      listBox.show();
      bottomBtn.find('js_p_l_more').removeClass('expend').find(".js_more_text").text("收起其它所有航班");
    };
  }
}
const init = config =>{
  moreFlight.init(config);
}
export default init;
